import axios from "axios"
import Vue from "vue"
import qs from "querystring"
import {errorAlert} from "../utils/alert"
import store from "../store"
import router from "../router"

//环境
if(process.env.NODE_ENV === "development"){
    Vue.prototype.$pre = "http://localhost:3000"
}else{
    Vue.prototype.$pre=""
}

//请求拦截
axios.interceptors.request.use(req=>{
    //每次请求都要做的逻辑
    //如果请求的接口不是登录，就要带请求头
    if(req.url!="/api/userlogin"){
        req.headers.authorization = store.getters.userInfo.token
    }
    return req
})

//响应拦截
axios.interceptors.response.use(res=>{
    //打印结果
    console.group("本次请求地址："+res.config.url);
    console.log(res);
    console.groupEnd()
    
    // //登录已过期或访问权限受限
    if(res.data.msg=="登录已过期或访问权限受限"){
        sessionStorage.removeItem("userInfo");
        router.replace("/login");
    }

    if(res.data.code!==200){
        errorAlert(res.data.msg)
    }
    return res
})

//封装get，post请求
export const get = (url,params={})=>{
    return axios({
        url,
        method:"get",
        params
    })
}

export const post =(url,data={},isFile=false)=>{
    let params = null;
    if(isFile){
        //有文件
        params= new FormData();
        for(let key in data){
            params.append(key,data[key])
        }
    }else{
        //无文件
        params=qs.stringify(data)
    }
    return axios({
        url,
        method:"post",
        data:params
    })
}